import { axios } from '@/utils/request' 
import FileSaver from 'file-saver'
import notification from 'ant-design-vue/es/notification'
import HmacSHA256 from 'crypto-js/hmac-sha256'

import Pinyin from 'js-pinyin'
Pinyin.setOptions({ charCase: 1 })
export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () { }
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function pinyin (value) {
  return Pinyin.getFullChars(value)
}
export function tableColumns (that, columns) {
  that.$nextTick(() => {
    for (
      let i = 0;
      i <
      document
        .getElementsByClassName('table-box')[0]
        .getElementsByClassName('ant-table-row')[0]
        .getElementsByTagName('td').length;
      i++
    ) {
      let maxWidth = 0
      if (
        document
          .getElementsByClassName('ant-table-row')[0]
          .getElementsByTagName('td')[i].clientWidth >
        document
          .getElementsByClassName('ant-table-thead')[0]
          .getElementsByTagName('th')[i].clientWidth
      ) {
        maxWidth = document
          .getElementsByClassName('ant-table-row')[0]
          .getElementsByTagName('td')[i].clientWidth
      } else {
        maxWidth = document
          .getElementsByClassName('ant-table-thead')[0]
          .getElementsByTagName('th')[i].clientWidth
      }
      that[columns][i].width = maxWidth
    }
    that.$forceUpdate()
  })
}

export function download (url, data, method = 'get', fileName) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      data,
      method: method, 
      responseType: 'blob'
    }).then((resp) => {
      console.log(resp, '123')
      try {
        FileSaver.saveAs(resp.data, fileName || resp.fileName)
        notification.success({
          message: '成功提示',
          description: '导出成功'
        })
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  })
} 

export async function paramsSign (config){
  const { url, method, data, baseURL, params, headers } = config
  console.log(url, baseURL)
  const requstBody = method.toUpperCase() === 'POST' ? data : ''
  const Timestamp = new Date().getTime()
  const NonceStr = '91xft' + new Date().getTime()
  const signStr = `${method.toUpperCase()}&${
    process.env.VUE_APP_CLIENTID
  }&${Timestamp}&${NonceStr}${ requstBody ? '&' + JSON.stringify(requstBody) : ''}`
  const Signature = await HmacSHA256(signStr, process.env.VUE_APP_SIGNKEY)
  headers['Client-Id'] = process.env.VUE_APP_CLIENTID
  headers['Nonce-Str'] = NonceStr
  headers['Timestamp'] = Timestamp
  headers['Signature'] = Signature.toString().toUpperCase()
  // headers["Client-Env"] = encodeURIComponent(JSON.stringify(ClientEnv));
  headers['Content-Type'] = 'application/json'
  //   'Content-Type': 'application/json;'
  return config
}